<?php
namespace app\api\model\food;

use app\common\model\User as UserModel;
use app\api\model\Applet as AppletModel;
use app\api\model\Setting as SettingModel;
use app\api\model\CouponUser as CouponUserModel;
use hema\wechat\Driver as Wechat;
use hema\wechat\WxBizDataCrypt;

/**
 * 用户模型类
 */
class User extends UserModel
{

    /**
     * 隐藏字段
     */
    protected $hidden = [
    ];

    /**
     * 获取用户信息
     */
    public static function getDetail($user_id)
    {
	    if($user = self::getUser(['user_id' => $user_id])){
            if($grade['lv'] = SettingModel::getItem('grade')){
                $grade['lv'][0]['image'] = base_url() . 'assets/img/v1.png';
                $grade['lv'][1]['image'] = base_url() . 'assets/img/v2.png';
                $grade['lv'][2]['image'] = base_url() . 'assets/img/v3.png';
                $grade['lv'][3]['image'] = base_url() . 'assets/img/v4.png';
                $grade['lv'][4]['image'] = base_url() . 'assets/img/v5.png';
                $grade['lv'][5]['image'] = base_url() . 'assets/img/v6.png';
                $grade['upper'] = $grade['lv'][5]['score']; //上一级所需积分
                $grade['lving'] = 100;//据升下一级完成百分比
                $grade['lack'] = 0;//升下一级所需积分
                $v = 6;
                for($n=5;$n>0;$n--){
                    if($user['score'] >= $grade['lv'][$n]['score']){
                        break;
                    }
                    $grade['upper'] = $grade['lv'][$n]['score']; //上一级所需积分
                    $v = $n+1; //用户等级
                    //判断下一级别
                    if($user['score'] < $grade['lv'][$n]['score'] AND $user['score'] >= $grade['lv'][$n-1]['score']){
                        $v = $n;
                        $m = $grade['upper'] - $grade['lv'][$n-1]['score']; //所需积分
                        $x = $user['score'] - $grade['lv'][$n-1]['score'];//已有积分
                        $grade['lving'] = round($x/$m*100); //计算已经完成百分比
                        $grade['lack'] = $m - $x;//计算还需要多少积分
                    }
                }
                //判断是否升级
                if($user['v'] < $v){
                    $user->v = $v;//升级
                    //升级任务
                    if(isset($grade['lv'][$v-1]['gift']) AND sizeof($grade['lv'][$v-1]['gift']) > 0){
                        $coupon = new CouponUserModel;
                        $coupon->add($grade['lv'][$v-1]['gift'],$user['user_id']);
                    }
                    $user->save();
                }
                $user['grade'] = $grade;
            }
            return $user;
        } 
        return false;
    }

    /**
     * 微信小程序用户登录
     */
    public function login(array $data)
    {
        $userInfo = json_decode(htmlspecialchars_decode($data['user_info']), true);
        //微信登录 (获取session_key)
        $wx = new Wechat;
        if(!$result = $wx->getComponentSessionKey($data['code'],$data['applet_id'])){
            $this->error = $wx->getError();
            return false;
        }
        if ($user = $this->where(['open_id' => $result['openid']])->find()) {
            $userInfo['nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $userInfo['nickName']);
            $userInfo['avatar'] = $userInfo['avatarUrl'];
            if (!$user->save($userInfo)) {
                $this->error = '用户信息更新失败';
                return false;
            }
            return $user;
        }
        $this->error = '用户不存在';
        return false;
    }
    
    /**
     * 微信小程序用户自动注册/登录
     */
    public function autoLogin(array $data)
    {
        //微信登录 (获取session_key)
        $wx = new Wechat;
        if(!$result = $wx->getComponentSessionKey($data['code'],$data['applet_id'])){
            $this->error = $wx->getError();
            return false;
        }
        if(isset($result['unionid'])){
            $userInfo['union_id'] = $result['unionid'];
        }
        if (!$user = $this->where(['open_id' => $result['openid']])->find()) {
            //用户不存在才执行
            $userInfo['open_id'] = $result['openid'];
            $userInfo['applet_id'] = $data['applet_id'];
            $userInfo['status'] = 10;
            $this->save($userInfo);
            $user = $this->where(['open_id' => $result['openid']])->find();
        }
        return $user;
    }

    /**
     * 获取用户手机号
     */
    public function getPhoneNumber($post, $userInfo)
    {
        // 微信登录 获取session_key
        $wx = new Wechat;
        if(!$result = $wx->getComponentSessionKey($post['code'],$post['applet_id'])){
            $this->error = $wx->getError();
            return false;
        }
        $sessionKey = $result['session_key'];
        $encryptedData= $post['encryptedData'];
        $iv = $post['iv'];
        $pc = new WxBizDataCrypt($sessionKey,$post['applet_id']);
        $errCode = $pc->decryptData($encryptedData,$iv,$data);
        $data = json_decode($data,true);
        if (isset($data['phoneNumber'])) {
            $userInfo->phone = $data['phoneNumber'];
            $userInfo->save();
            return true;
        }
        return false;
    }

    /**
     * 公众号授权登陆
     */
    public function auth($code,$appid)
    {
        $wx = new Wechat;
        $session = $wx->oauth2($code,$appid,self::$applet_id);
        if (isset($session['errcode'])) {
            $this->error = 'code换取网页授权access_token失败！code：'.$session['errcode'].'，msg：' . $session['errmsg'];
            return false;
        }
        if (!$user = $this->where(['open_id' => $session['openid']])->find()) {
            //用户不存在才执行
            $result = $wx->getUserinfo($session['openid'],$session['access_token']);
            if (isset($result['errcode'])) {
                $this->error = '获取用户资料失败！code：'.$result['errcode'].'，msg：' . $result['errmsg'];
                return false;
            }
            if(isset($result['unionid'])){
                $data['union_id'] = $result['unionid'];
            }
            $data['open_id'] = $result['openid'];
            $data['nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $result['nickname']);
            $data['avatar'] = $result['headimgurl'];
            $data['gender'] = $result['sex'];
            $data['country'] = $result['country'];
            $data['province'] = $result['province'];
            $data['city'] = $result['city'];
            $data['platform'] = 20; //H5平台
            $data['status'] = 10; //商家会员
            $data['applet_id'] = self::$applet_id;
            $this->save($data);
            $user = $this->where(['open_id' => $result['openid']])->find();
        }
        return $user;
    }
}
